<?php
/**
 * Created by PhpStorm.
 * User: shaowei
 * Date: 2018/12/21
 * Time: 上午11:44
 */

namespace App\Http\Services;

use App\Http\Model\Ad;
use App\Http\Model\Ad as AdModel;
use App\Http\Model\Hint;
use App\Http\Model\Room;
use App\Http\Model\Template as TemplateModel;
use App\Http\Model\User;
// use App\Modules\Mq\Tasks\AdTimingPushTask;
use Illuminate\Support\Facades\Redis;

class AdServices extends CommonServices
{
    private $adModel;
    private $serviceMsg;
    protected $user;
    protected $templateModel;
    protected $roomModel;

    //用户banner缓存
    protected $userBannerKey = 'USERBANNER:';//string USERBANNER:{userId}:{type} => {string}

    public function __construct()
    {
        $this->adModel = new AdModel();
        $this->serviceMsg = new MsgServices();
        $this->user = new User();
        $this->templateModel = new TemplateModel();
        $this->roomModel = new Room();

    }


    /**
     * 新版本获取banner服务
     * @param int $type
     * @return mixed|null
     * @author  
     */
    public function get_banner($type=0,$userid, $roomId)
    {
        $data = $this->adModel->get_banner($type, $userid, [], $roomId);
        if(!empty($data)) {
            $ids = array_column($data, 'id');
            sort($ids);
            Redis::set($this->userBannerKey.$userid.':'.$type, implode(',', $ids));
        }
        return $data;
    }

    /**
     * 兼容老版本接口获取活动弹窗开屏
     * @return array`
     */
    public function get_customer(){
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            $type = isset($this->requestData['type']) ? intval($this->requestData['type']) : 0;
            $res = $this->parse_app_UA();
            $channel_no = 0;
            if (!empty($res['channel_id'])){
                $channel_no = $res['channel_id'];
            }
            $userId = $this->requestData['user_id'] ?? 0;
            if(empty($type)){
                $code = Hint::PARAM_ERROR;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }

            $param = [];
            $param['user_id'] = $userId;
            if($type ==6){
                $param['channel_no'] = $channel_no;
                $userInfo = $this->user->get_user($userId);
                $param['user_cat'] = $userInfo['user_cat'];
                if(!empty($userInfo['gender'])){
                    $param['gender'] = $userInfo['gender'];
                }
            }
            $user = $this->user->get_current_user();
            //广告弹窗
            if($type == 10){
                $times = $this->adModel->getPopUpTimes($user['user_id']);
                if($times >=5){
                    break;
                }else{
                    $this->adModel->setPopUpTimes($user['user_id']);
                }
            }
            $test_user_ids = $this->user->get_test_users();
            if(in_array($user['user_id'] ,$test_user_ids)){
                $data = $this->adModel->get_customer_no_limit($type);
            }else{
                $data = $this->adModel->get_customer($type,$param);
            }

            $tempData = [];
            if ($type == 3 || $type == 5) {//过滤`充值活动`入口
                $userFilterService = new UserFilterServices();
                foreach ($data as $value) {
                    if ($value['name'] == '充值活动') {
                        $userStatus = (new FirstRechargeServices())->checkUserStatus($user['user_id']);
                        if ($userStatus === false) {
                            continue;
                        }
                    }

                    if ($userFilterService->getUserFilterResult($user['user_id']) === false) {
                        continue;
                    }

                    $tempData[] = $value;
                }

                $data = $tempData;
            }

            // 如果是type = 6 则添加活动是否开始的字段 add by zxiaofee
            if ($type == 6) {
                $curTime = time();
                foreach ($data as $k =>$v) {
                    $data[$k]['has_begun'] = false;
                    if ($v['start_timestamp'] < $curTime and $v['end_timestamp'] > $curTime) {
                        $data[$k]['has_begun'] = true;
                    }
                    unset( $data[$k]['start_timestamp']);
                    unset( $data[$k]['end_timestamp']);
                }
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 后台API
     * 广告创建
     * @author  
     * */
    public function adCreate()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            try {
                $this->I('name', '广告名称', 'string', true, '广告名称不能为空');
                $this->I('img', '广告图片', 'string', true, '广告图片不能为空');
                $this->I('type', '广告类型', 'int', true, '广告类型不能为空');// （位置）0:banner 3：房间内 5：小窝
                $this->I('start_timestamp', '开始时间', 'string', false, '开始时间不能为空');
                $this->I('end_timestamp', '结束时间', 'string', false, '结束时间不能为空');
                $this->I('mincharm', '最小魅力值', 'int', false, '最小魅力值不能为空');
                $this->I('maxcharm', '最大魅力值', 'int', false, '最大魅力值不能为空');
                $this->I('minrich', '最小财富值', 'int', false, '最小财富值不能为空');
                $this->I('maxrich', '最大财富值', 'int', false, '最大财富值不能为空');

                $this->I('minmoney', '最小充值', 'int', false, '最小充值不能为空');
                $this->I('maxmoney', '最大充值', 'int', false, '最大充值不能为空');
                $this->I('status', '状态', 'int', true, '状态不能为空');// 0:正常 1:关闭
                $this->I('sort', '广告顺序', 'string', true, '广告顺序不可为空');
                $this->I('action', '跳转', 'string', false, '跳转');
                $this->I('user_cat', '用户群组', 'int', false, '用户群组');
                $this->I('gift_id', '礼物ID', 'string', false, '礼物ID不能为空');
                $this->I('room_ids','房间id', 'string', false, '房间id');

                //检查sort排序是否唯一
                $cheksort = AdModel::where("sort",$this->requestData['sort'])->exists();
                if ($cheksort)
                {
                    $code = Hint::ERR_SYS_FAIL;
                    $msg = '排序值重复';
                    break;
                }
                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化
                //若开始时间为空则取默认添加时间
                if (!empty($this->requestData['start_timestamp'])) {
                        $this->requestData['start_timestamp'] = strtotime($this->requestData['start_timestamp']);
                }else{
                    $this->requestData['start_timestamp'] = time();
                }
                //结束时间为空时候表示不做结束判断处理
                if (!empty($this->requestData['end_timestamp'])) {
                    $this->requestData['end_timestamp'] = strtotime($this->requestData['end_timestamp']);
                }
                $this->requestData['status'] = $this->requestData['status']  ?? 0;//上下架状态0正常1关闭
                $this->requestData['user_cat'] = $this->requestData['user_cat']  ?? 0;//用户分类0全部1主播2用户
                //间隔时间小窝时候5秒
                if ($this->requestData['type'] == 5)
                {
                    $this->requestData['auto_time'] = 5;
                }
                $data['id'] = $this->adModel->insertSingle($this->requestData);
                if ($data['id'] <= 0) {
                    $code = Hint::ERR_DATA_CREATE_FAIL;
                    $msg = '广告' . Hint::getErrCodeMsg($code);
                    break;
                }
            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 后台API
     * 广告更新
     * @author  
     * */
    public function adUpdate()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('name', '广告名称', 'string', true, '广告名称不能为空');
                $this->I('img', '广告图片', 'string', true, '广告图片不能为空');
                $this->I('type', '广告类型', 'int', true, '广告类型不能为空');// （位置）0:banner 3：房间内 5：小窝
                $this->I('start_timestamp', '开始时间', 'string', false, '开始时间不能为空');
                $this->I('end_timestamp', '结束时间', 'string', false, '结束时间不能为空');
                $this->I('mincharm', '最小魅力值', 'int', false, '最小魅力值不能为空');
                $this->I('maxcharm', '最大魅力值', 'int', false, '最大魅力值不能为空');
                $this->I('minrich', '最小财富值', 'int', false, '最小财富值不能为空');
                $this->I('maxrich', '最大财富值', 'int', false, '最大财富值不能为空');

                $this->I('minmoney', '最小充值', 'int', false, '最小充值不能为空');
                $this->I('maxmoney', '最大充值', 'int', false, '最大充值不能为空');
                $this->I('status', '状态', 'int', true, '状态不能为空');// 0:正常 1:关闭
                $this->I('sort', '广告顺序', 'string', true, '广告顺序不可为空');
                $this->I('action', '跳转', 'string', false, '跳转');
                $this->I('id', '编辑id', 'int', true, '编辑id');
                $this->I('user_cat', '用户群组', 'int', false, '用户群组');
                $this->I('gift_id', '礼物ID', 'int', false, '礼物ID不能为空');
                $this->I('room_ids','房间id', 'string', false, '房间id');

                //检查sort排序是否唯一
                $cheksort = AdModel::where("sort",$this->requestData['sort'])->where('id','!=',$this->requestData['id'])->exists();
                if ($cheksort)
                {
                    $code = Hint::ERR_SYS_FAIL;
                    $msg = '排序值重复';
                    break;
                }
                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化
                $id = $this->requestData['id'];

                // 移除请求数据中的ID
                unset($this->requestData['id']);

                if (empty($this->requestData)) {
                    $code = Hint::ERR_PARAMS_CHECK_FAIL;
                    $msg = Hint::getErrCodeMsg($code) . ':至少包含任意一个业务参数';
                    break;
                }
                //若开始时间为空则取默认添加时间
                if (!empty($this->requestData['start_timestamp'])) {
                    $this->requestData['start_timestamp'] = strtotime($this->requestData['start_timestamp']);
                }else{
                    $this->requestData['start_timestamp'] = time();
                }
                //结束时间为空时候表示不做结束判断处理
                if (!empty($this->requestData['end_timestamp'])) {
                    $this->requestData['end_timestamp'] = strtotime($this->requestData['end_timestamp']);
                }
                $this->requestData['status'] = $this->requestData['status']  ?? 0;//上下架状态0正常1关闭
                $this->requestData['user_cat'] = $this->requestData['user_cat']  ?? 0;//用户分类0全部1主播2用户
                //间隔时间小窝时候5秒
                if ($this->requestData['type'] == 5)
                {
                    $this->requestData['auto_time'] = 5;
                }
                Ad::where('id',$id)->update($this->requestData);

            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 后台广告删除API
     * 广告删除
     * @author  
     * */
    public function adRemove()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('id', '广告ID', 'int', true, '广告ID不能为空');

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化
                $ad = $this->adModel->get_ad($this->requestData['id']);
                $ret = $this->adModel->singleRemove($this->requestData);
                if (!$ret) {
                    $code = Hint::ERR_DATA_REMOVE_FAIL;
                    $msg = '广告' . Hint::getErrCodeMsg($code);
                    break;
                }
                //删除：判断type为房间/小屋/关注条 发消息通知客户端
                if(in_array($ad['type'] ,array(3, 4, 5))){
                    $data['type'] = $ad['type'];
                    $data['params'] = $this->adModel->get_customer($ad['type']);
                }
            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }
}
